package org.sean.framework.canary.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.sean.framework.canary.core.CanaryUtils;
import org.sean.framework.util.ObjectUtil;
import org.sean.framework.web.holder.RequestHolder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 灰度拦截器
 *
 * @author xielei
 */
public class CanaryInterceptor implements RequestInterceptor {

    private static final String KEY_SERVER_NAME = "from-server-name";
    private static final String KEY_SERVER_IP = "from-server-ip";
    private static final String KEY_SERVER_ID = "from-server-id";

    private static List<String> serverName;
    private static List<String> serverIp;
    private static List<String> serverId;
    private static boolean isSetup = false;

    @Override
    public void apply(RequestTemplate template) {
        Map<String, Collection<String>> headers = new HashMap<>();
        if (!isSetup) {
            try {
                serverName = Collections.singletonList(CanaryUtils.getLocalServiceId());
                serverIp = Collections.singletonList(CanaryUtils.getLocalIp());
                serverId = Collections.singletonList(CanaryUtils.getLocalInstanceId());
                isSetup = true;
            } catch (Exception e) {
                // do nothing
            }
        }
        headers.put(KEY_SERVER_NAME, serverName);
        headers.put(KEY_SERVER_IP, serverIp);
        headers.put(KEY_SERVER_ID, serverId);

        if (ObjectUtil.isNotEmpty(RequestHolder.getHeaders())) {
            template.headers(RequestHolder.getCollectionHeaders());
        }
        headers.remove(HttpHeaders.CONTENT_TYPE);
        headers.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
        template.removeHeader(HttpHeaders.CONTENT_TYPE);
        if (ObjectUtil.isNotEmpty(headers)) {
            template.headers(headers);
        }
    }
}
